// file: handler/handler.go
package handler

import (
  "context"
  "sync"

  html2md "github.com/JohannesKaufmann/html-to-markdown"
  "github.com/cloudwego/hertz/pkg/app"
  "github.com/cloudwego/hertz/pkg/common/utils"
  "github.com/cloudwego/hertz/pkg/protocol/consts"
  "palywright-go-server/playwrightpool"
)

var (
  poolInstance *playwrightpool.Pool
  once         sync.Once
)

// getPoolInstance 懒加载初始化全局的 Playwright 会话池（例如池大小设置为 5）
func getPoolInstance() *playwrightpool.Pool {
  once.Do(func() {
    var err error
    poolInstance, err = playwrightpool.NewPool(5)
    if err != nil {
      // 初始化失败时直接 panic，也可根据实际需求处理
      panic(err)
    }
  })
  return poolInstance
}

// 根据传入的 url 获取网页 HTML 并返回给客户端
func Fetch(ctx context.Context, reqCtx *app.RequestContext) {
  url := reqCtx.Query("url")
  format := reqCtx.Query("format")
  if url == "" {
    reqCtx.JSON(consts.StatusBadRequest, utils.H{"code": 0, "msg": "缺少 url 参数"})
    return
  }

  pool := getPoolInstance()
  html, err := pool.FetchHTML(url)
  if err != nil {
    reqCtx.JSON(consts.StatusInternalServerError, utils.H{"code": 0, "msg": err.Error()})
    return
  }

  // 如果 format == markdown，则将 HTML 转换为 Markdown 格式
  if format == "markdown" {
    converter := html2md.NewConverter("", true, nil)
    markdownText, err := converter.ConvertString(html)
    if err != nil {
      reqCtx.JSON(consts.StatusInternalServerError, utils.H{"code": 0, "msg": "转换 markdown 失败: " + err.Error()})
      return
    }
    reqCtx.String(consts.StatusOK, markdownText)
    return
  }

  // 默认返回 HTML
  reqCtx.String(consts.StatusOK, html)
}
